package cn.chiship.sdk.core.encryption.rsa;

import cn.chiship.sdk.core.util.Base64Util;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * @author lijian
 */
public class RsaTest {

	private static final Logger log = LoggerFactory.getLogger(RsaTest.class);

	public static void main(String[] args) {

		Long start = System.currentTimeMillis();
		// 获取公钥和私钥
		String[] keys = RsaEncrypt.genKeyPair();
		String publicKey = keys[0];
		String privateKey = keys[1];
		log.info("用时：{}毫秒", (System.currentTimeMillis() - start));

		log.info("公钥：{}", publicKey.length());
		log.info("私钥：{}", privateKey.length());

		log.info("--------------前端--后台，公钥加密私钥解密过程-------------------");
		String plainText = "admin123";
		// 公钥加密过程
		byte[] cipherData = RsaEncrypt.encrypt(RsaEncrypt.loadPublicKeyByStr(publicKey), plainText.getBytes());
		String cipher = Base64Util.encode(cipherData);
		// 私钥解密过程
		byte[] res = RsaEncrypt.decrypt(RsaEncrypt.loadPrivateKeyByStr(privateKey), Base64Util.decode(cipher));
		String restr = new String(res);
		log.info("原文：{}", plainText);
		log.info("加密：{}", cipher);
		log.info("解密：{}", restr);

		log.info("--------------后台--前端，私钥加密公钥解密过程-------------------");
		plainText = "success登录成功";
		// 私钥加密过程
		cipherData = RsaEncrypt.encrypt(RsaEncrypt.loadPrivateKeyByStr(privateKey), plainText.getBytes());
		cipher = Base64Util.encode(cipherData);
		// 公钥解密过程
		res = RsaEncrypt.decrypt(RsaEncrypt.loadPublicKeyByStr(publicKey), Base64Util.decode(cipher));
		restr = new String(res);
		log.info("原文：{}", plainText);
		log.info("加密：{}", cipher);
		log.info("解密：{}", restr);

		log.info("---------------私钥签名过程------------------");
		String content = "Zxzdads05d2a12";
		String signstr = RsaSignature.sign(content, privateKey);
		log.info("签名原串：{}", content);
		log.info("签名串：{}", signstr);

		log.info("---------------公钥校验签名------------------");
		log.info("签名原串：{}", content);
		log.info("签名串：{}", signstr);
		log.info("验签结果：{}", RsaSignature.doCheck(content, signstr, publicKey));
		publicKey = "MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQDtHRNJLOSp6ggzJOc6aqxh/dBkOOtgOYdoqIa8KXoaAyh5K4jBsMdN7aF9JyUOu/HxzxhQn0TNEYwDtG04p6psL4Oy5vINVkgt2il/hXYm8RdGbay33v7xvZRo2QEKsaWoAiFcHIPceQfCO9/9EDAG6SccpDjYvutVJRpRcM0K8wIDAQAB";

		log.info("验签结果：{}", RsaSignature.doCheck("05d2a12",
				"c0+ScLd5RmmWJ7iLoecfK3NNkLerYWamDz8dV9PhXUhPWMIBpj0rQTYX0nZhiu1CPTpz4ha27ywX3Ew3W0qDVtwNss8omiW0jmz03MuRVPSx0UJRosTxPPkhhBbo/r1cT1CtEb3rNHhypeMWQkBZPMfW3hpcg7UH96qiJT6EDGM=",
				publicKey));

	}

}
